import {ScrollView, View, Text, Image, Input, Textarea, Video} from '@tarojs/components';
import React, {Component} from 'react';
import Taro, {getCurrentInstance} from '@tarojs/taro';
import {connect} from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';
import {returnTime} from '@/utils/returnTime';
import 'taro-ui/dist/style/components/input.scss';
import 'taro-ui/dist/style/components/icon.scss';
import CommentList from './components/CommentList';

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  textInput: any;
  constructor(props) {
    super(props);
    this.state = {
      refresherTriggered: false,
      commentValue: '',
    };
  }

  componentDidMount() {}

  componentDidShow() {
    let {type} = getCurrentInstance().router.params;
    if (type) {
      // input聚焦
      // this.textInput.focus();
    }
    this.props.actions.init();
  }

  componentWillUnmount() {}

  onShareAppMessage = (res) => {
    let {user} = Taro.getStorageSync('b2b-wechat@login');
    let {
      main: {detail},
      actions: {action},
    } = this.props;
    let arr = [];
    let path = `/pages/package-B/community-detail/index?id=${detail.id}&del=false`;
    let title = `【${user.name}】为您推荐`;
    let imageUrl = `https://shang-cloud.oss-cn-nanjing.aliyuncs.com/assets/image/none/share.png`;
    if (detail.url) {
      arr = detail.url.split(';');
      imageUrl = arr[0];
    }
    //页面内分享按钮
    return {
      title,
      imageUrl,
      path,
    };
  };

  //图片渲染
  renderImg(list) {
    let listView = [];
    let urls = [];
    if (list.length > 0) {
      list.map((item, index) => {
        if (item == '') {
          return;
        }
        urls.push(item);
        listView.push(
          <Image
            key={item}
            onClick={this.onImageClick.bind(this, item, urls)}
            src={item}
            mode="widthFix"
            className="b_img"
          />,
        );
      });
    }
    return listView;
  }
  onImageClick = (item, urls) => {
    this.previewImage(item, urls);
  };
  previewImage = (img, files) => {
    Taro.previewImage({
      current: img, // 当前显示图片的http链接
      urls: files, // 需要预览的图片http链接列表
    });
  };

  async submitPost() {
    let {commentValue} = this.state;
    let {
      main: {detail},
      actions: {action},
    } = this.props;
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    if (!itemStr) {
      Taro.navigateTo({
        url: '/pages/package-C/login/login/index',
      });
      return;
    } else {
      let userInfo = itemStr.user;
      let params = {
        forumid: detail.id,
        content: commentValue,
        userId: userInfo.id,
      };
      action.addComment(params);
      this.setState({commentValue: ''});
    }
  }

  _onScrollToLower = () => {
    let {
      main: {pageNum, totalPages},
      actions: {action},
    } = this.props;
    let num = pageNum + 1;
    if (pageNum == totalPages) return;
    this.props.actions.action.commonChange('main.pageNum', num);
    this.props.actions.action.findCommentList();
  };

  _onRefresherRefresh = () => {
    let {refresherTriggered} = this.state;
    if (refresherTriggered) return;
    this.setState({
      refresherTriggered: true,
    });
    this.props.actions.action.commonChange('main.pageNum', 1);
    this.props.actions.action.findCommentList();
    setTimeout(() => {
      this.setState({
        refresherTriggered: false,
      });
    }, 2000);
  };

  render() {
    let {commentValue, refresherTriggered} = this.state;
    let {
      main: {detail, commentList},
      actions: {action},
    } = this.props;
    return (
      <View className="packageBCommunityDeatil">
        <ScrollView
          className="scrollView"
          onScrollToLower={this._onScrollToLower}
          refresherEnabled
          refresherTriggered={refresherTriggered}
          onRefresherPulling={this._onRefresherRefresh}
          scrollY
        >
          <View
            style={{
              paddingTop: '30rpx',
              paddingLeft: '30rpx',
              paddingRight: '30rpx',
            }}
          >
            <View className="R_SB">
              <View
                style={{
                  flexDirection: 'row',
                  alignContent: 'center',
                  justifyContent: 'center',
                }}
              >
                <View
                  style={{
                    width: '70rpx',
                    height: '70rpx',
                    borderRadius: '35rpx',
                    overflow: 'hidden',
                  }}
                >
                  <Image
                    style={{
                      width: '70rpx',
                      height: '70rpx',
                    }}
                    mode="aspectFill"
                    src={detail.userImg}
                  />
                </View>
                <View
                  style={{
                    marginLeft: '30rpx',
                    flexDirection: 'column',
                    alignContent: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Text className="f_28">{detail.userName}</Text>
                  <Text className="f_22">{returnTime(detail.publishDate)}</Text>
                </View>
              </View>
            </View>
            {detail.content ? <Text className="T_title">{detail.content}</Text> : null}
          </View>
          <View className="R_W">
            {detail.videoUrl != '' && detail.videoUrl ? (
              <Video
                style={{
                  width: '92vw',
                  height: '600rpx',
                  borderRadius: '10rpx',
                  marginLeft: '30rpx',
                  marginBottom: '10rpx',
                }}
                src={detail.videoUrl}
                initialTime={0}
                controls
                autoplay={false}
                loop={false}
                muted={false}
              />
            ) : null}
            {detail.url != '' && detail.url ? this.renderImg(detail.url.split(';')) : null}
          </View>
          <View className="c_box">
            <Text className="f_28">全部评论</Text>
          </View>
          <View className="postCont">
            <CommentList></CommentList>
          </View>
        </ScrollView>
        <View className="keyBoard">
          <View className="inputBox">
            <Textarea
              className="searchText"
              maxlength={127}
              // type="text"
              placeholder={commentList.length == 0 ? '还没有人留言呢，你来做第一个吧～' : '期待您的评论～'}
              value={commentValue}
              ref={(input) => {
                this.textInput = input;
              }}
              onInput={(e) => {
                // let str = '';
                // if (e.detail.value) {
                //   let zz = e.detail.value.replace(
                //     /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g,
                //     '',
                //   );
                //   str = zz.replace(/[`~!@#$%^&*()=+|{}.<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？':;']/g, '');
                // }
                this.setState({
                  commentValue: e.detail.value,
                });
              }}
            />
          </View>
          <View
            style={{
              marginLeft: '15px',
            }}
          >
            <View
              style={{
                width: '150rpx',
                height: '60rpx',
                lineHeight: '60rpx',
                borderRadius: '100rpx',
                backgroundColor: '#218CFF',
              }}
              onClick={() => {
                if (detail.status == 0) {
                  Taro.showToast({
                    title: '帖子审核中，暂不支持操作！',
                    icon: 'none',
                    duration: 2000,
                  });
                  return;
                } else if (detail.status == 1) {
                  this.submitPost();
                } else if (detail.status == 2) {
                  Taro.showToast({
                    title: '帖子审核未通过，暂不支持操作！',
                    icon: 'none',
                    duration: 2000,
                  });
                  return;
                }
              }}
            >
              <Text
                style={{
                  fontSize: '28rpx',
                  color: '#fff',
                  textAlign: 'center',
                  lineHeight: '58rpx',
                }}
              >
                发送
              </Text>
            </View>
          </View>
        </View>
      </View>
    );
  }
}
